package com.hejia.bulbul.scheduler;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;

import com.hejia.alauda.entity.DayInventory;
import com.hejia.alauda.service.StatisticService;

/**
 * 每天定时查询当天总保有量
 * 
 * @author jatin
 *
 */
public class InventoryScheduler {

	private static final Log Logger = LogFactory
			.getLog(PaymentCollectionInStockScheduler.class);

	@Resource
	private StatisticService statisticService;

	@Resource
	private StatisticService dayInventoryService;

	// [秒] [分] [小时] [日] [月] [周] [年]
	@Scheduled(cron = "0 30 0 * * ?")
	@Async("executor")
	public void inventoryCalculate() {

		Logger.info("开始计算");
		try {
			SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
			Calendar ca = Calendar.getInstance();
			ca.add(Calendar.DATE, -1);
			String statdate = date.format(ca.getTime());// 统计日期

			/*
			 * 获取数据
			 */
			BigDecimal trendAmount = (BigDecimal) statisticService
					.stattrendByMonth(statdate).get("inven");
			trendAmount = trendAmount != null ? trendAmount : new BigDecimal(0);// 总保有量
			Double capital = statisticService.selectIntoDayinventory(statdate,
					"capital");
			capital = capital != null ? capital : (double) 0;// 当日本金
			Double payment = statisticService.selectIntoDayinventory(statdate,
					"payment");
			payment = payment != null ? payment : (double) 0;// 当日兑付
			Double sale = statisticService.selectIntoDayinventory(statdate,
					"sale");
			sale = sale != null ? sale : (double) 0;// 当日销售量
			Double interests = payment - capital;// 当日利息

			/*
			 * 插入数据
			 */
			DayInventory dayInventory = new DayInventory();
			dayInventory.setCreateDate(new Date());
			dayInventory.setStatDate(ca.getTime());
			dayInventory.setAmount(trendAmount);
			dayInventory.setCapital(new BigDecimal(capital));
			dayInventory.setPayment(new BigDecimal(payment));
			dayInventory.setSale(new BigDecimal(sale));
			dayInventory.setInterests(new BigDecimal(interests));

			Integer flag = dayInventoryService.selectInventory(statdate);
			if (flag >= 1) {
				dayInventoryService.deleteInventory(statdate);
			}

			dayInventoryService.saveDayInventory(dayInventory);

			Logger.info("结束插入数据");
		} catch (Exception e) {
			Logger.error("插入数据失败", e);
		}
	}

}
